//
//  FeedsViewController.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/18.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift
import MJRefresh
import Toast


class FeedsViewController: UIViewController {
    
    private lazy var refreshHeader: MJRefreshNormalHeader = {
        guard let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(FeedsViewController.fetchLatestData)) else { fatalError() }
        header.setTitle("下拉刷新", for: .idle)
        header.setTitle("松手立即刷新", for: .pulling)
        header.setTitle("正在刷新...", for: .refreshing)
        header.lastUpdatedTimeLabel.isHidden = true
        return header
    }()
    
    private lazy var refreshFooter: MJRefreshAutoNormalFooter = {
        guard let footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(FeedsViewController.fetchMoreData)) else { fatalError() }
        footer.setTitle("上拉加载", for: .idle)
        footer.setTitle("上拉加载", for: .pulling)
        footer.setTitle("正在加载...", for: .refreshing)
        footer.setTitle("已加载全部数据", for: .noMoreData)
        return footer
    }()
    
    private lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: 175 * UIScreen.screenScale, height: 260 * UIScreen.screenScale)
        return layout
    }()
    
    private lazy var collectionView: FeedsCollectionView = {
        let collectionView = FeedsCollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.allowsSelection = false
        collectionView.backgroundColor = .clear
        collectionView.register(FeedsCell.self, forCellWithReuseIdentifier: "\(FeedsCell.self)")
        collectionView.dataSource = self
        collectionView.contentInset = UIEdgeInsets(top: 5, left: 8, bottom: 20, right: 8)
        collectionView.mj_header = refreshHeader
        return collectionView
    }()
    
    private let viewModel: FeedsViewModel
    
    var isFetchData = false {
        willSet {
            guard newValue else { return }
            if newValue == isFetchData { return }
            fetchLatestData()
        }
    }
    
    init(categoryItem: FeedsCategory.CategoryItem) {
        viewModel = FeedsViewModel(categoryItem: categoryItem)
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
}

private extension FeedsViewController {
    func setupUI() {
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
    
    @objc func fetchLatestData() {
        guard checkNetworkReachable() else { return self.refreshHeader.endRefreshing() }
        _ = viewModel.fetchLatestData()
            .subscribe(onNext: { [weak self] _ in
                guard let self = self else { return }
                self.refreshHeader.endRefreshing()
                self.collectionView.reloadData()
                if self.viewModel.isTheLastPage {
                    self.refreshFooter.endRefreshingWithNoMoreData()
                } else {
                    self.refreshFooter.resetNoMoreData()
                    self.collectionView.mj_footer = self.refreshFooter
                }
            }, onError: { [weak self] (error) in
                guard let self = self else { return }
                self.refreshHeader.endRefreshing()
                self.showFetchError(error)
            })
    }
    
    @objc func fetchMoreData() {
        guard checkNetworkReachable() else { return self.refreshFooter.endRefreshing() }
        _ = viewModel.loadMoreData()
            .subscribe(onNext: { [weak self] _ in
                guard let self = self else { return }
                self.collectionView.reloadData()
                if self.viewModel.isTheLastPage {
                    self.refreshFooter.endRefreshingWithNoMoreData()
                } else {
                    self.refreshFooter.endRefreshing()
                }
            }) { [weak self] (error) in
                guard let self = self else { return }
                self.refreshFooter.endRefreshing()
                self.showFetchError(error)
            }
    }
    
    func checkNetworkReachable() -> Bool {
        let reachable = Network.isReachable
        if !reachable {
            view.makeCenterMsg("网络不可用")
        }
        return reachable
    }
    
    func showFetchError(_ error: Error) {
        #if DEBUG
        view.makeCenterMsg(error.localizedDescription)
        #else
        view.makeCenterMsg("网络开小差啦~~~")
        #endif
    }
}

extension FeedsViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.feeds.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(FeedsCell.self)", for: indexPath)
        if let feedCell = cell as? FeedsCell {
            feedCell.configData(with: viewModel.feeds[indexPath.item])
        }
        return cell
    }
}
